package com.fjwt.gz.task.config.couponReceipt;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fjwt.gz.core.utils.SpringBeansUtil;
import com.fjwt.gz.db.entity.AwardSettingEntity;
import com.fjwt.gz.db.entity.FansAwardEntity;
import com.fjwt.gz.province.inter.BankCardService;
import com.fjwt.gz.service.impl.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 卡券回执校验
 */
@Slf4j
@Component
public class CouponReceiptTask {

    @Autowired
    private FansAwardService fansAwardService;
    @Autowired
    private AwardSettingService awardSettingService;

    @Value("${province.code}")
    private String provinceCode;

    private static final int QUERY_PAGE_SIZE = 100; //每次查询数量

//    @Scheduled(cron = "${cron.CouponReceiptTask}")//每天执行一次
    @Transactional
    public void start() {
        log.info("开始进入卡券回执校验定时任务，开始时间:{}", DateUtil.now());

        LambdaQueryWrapper<FansAwardEntity> gw = FansAwardEntity.gw()
                .eq(FansAwardEntity::getReceiptState, 1)
                .isNotNull(FansAwardEntity::getExtraJson);

        int currentPageIndex = 1; //当前页码
        while (true) {
            try {
                IPage<FansAwardEntity> fansAwardEntityIPage = fansAwardService.page(new Page(currentPageIndex, QUERY_PAGE_SIZE), gw);
                log.info("查询页数：{}，size:{}，结果list：{}", currentPageIndex, QUERY_PAGE_SIZE, JSONUtil.toJsonStr(fansAwardEntityIPage));

                if (fansAwardEntityIPage == null || fansAwardEntityIPage.getRecords().isEmpty()) { //本次查询无结果, 不再继续查询;
                    break;
                }

                for (FansAwardEntity fansAwardEntity : fansAwardEntityIPage.getRecords()) {
                    // 回执类型校验
                    String receiptTypeStr = "";
                    log.info("此时处理的数据的是：{}", JSONUtil.toJsonStr(fansAwardEntity));
                    LambdaQueryWrapper<AwardSettingEntity> awardSettingGw = AwardSettingEntity.gw();
                    awardSettingGw.eq(AwardSettingEntity::getAwardId, fansAwardEntity.getAwardId());
                    awardSettingGw.eq(AwardSettingEntity::getAwardType, fansAwardEntity.getAwardType());
                    AwardSettingEntity awardSettingEntity = awardSettingService.getOne(awardSettingGw);

                    log.info("奖品配置信息：{}", JSONUtil.toJsonStr(awardSettingEntity));
                    if (ObjectUtils.isEmpty(awardSettingEntity) || ObjectUtils.isEmpty(awardSettingEntity.getReceiptType())) {
                        log.info("回执类型为空，跳过");
                        continue;
                    }
                    receiptTypeStr = awardSettingEntity.getReceiptType();

                    JSONObject extraJson = JSONObject.parseObject(fansAwardEntity.getExtraJson());
                    JSONObject receiptContent = extraJson.getJSONObject("receiptContent");
                    log.info("回执信息：{}", JSONUtil.toJsonStr(receiptContent));
                    if (ObjectUtils.isEmpty(receiptContent)) {
                        log.info("奖品附加数据字段不包含回执信息，跳过");
                        continue;
                    }

                    // 是否校验通过
                    boolean isPass = true;

                    // 校验接口类型
                    String[] receiptTypes = receiptTypeStr.split(",");
                    for (String receiptType : receiptTypes) {
                        boolean result = true;
                        switch (receiptType) {
                            case "1":
                            case "2":
                                result = getBankCardInfo(receiptType, null, receiptContent.getString("bankCard"), null, null);
                                if (!result) {
                                    isPass = false;
                                }
                                break;
                            case "3":
                                result = getBankCardInfo(receiptType, null, receiptContent.getString("bankCard"), receiptContent.getString("openDate"), null);
                                if (!result) {
                                    isPass = false;
                                }
                                break;
                            case "4":
                                result = getBankCardInfo(receiptType, null, receiptContent.getString("bankCard"), receiptContent.getString("depositDate"), receiptContent.getDouble("deposit"));
                                if (!result) {
                                    isPass = false;
                                }
                                break;
                            default:
                                result = false;
                                isPass = false;
                        }
                        log.info("校验类型：{}，校验结果：{}", receiptType, result);
                    }

                    log.info("fansAwardId：{}，校验结果：{}", fansAwardEntity.getFansAwardId(), isPass);
                    // 校验通过
                    if (isPass) {
                        fansAwardEntity.setReceiptState(2);
                        fansAwardEntity.setReceiptVerifyTime(DateUtil.date());
                        fansAwardService.updateById(fansAwardEntity);
                    }
                }
                currentPageIndex ++;
            } catch (Exception e) { //出现异常，直接退出，避免死循环。
                log.error("error", e);
                break;
            }
        }
        log.info("结束卡券回执校验定时任务，结束时间:{}", DateUtil.now());
    }

    /**
     * 获取银行卡信息
     */
    public boolean getBankCardInfo(String type,String custNo, String bankCard, String date, Double deposit) {
        BankCardService bankCardService = SpringBeansUtil.getBean(provinceCode + "BankCardService", BankCardService.class);
        if (ObjectUtils.isEmpty(bankCardService)) {
            log.info("{}，实现接口不存在", provinceCode);
            return false;
        }
        List<JSONObject> jsonObjects = new ArrayList<>();
        JSONObject jsonObject = new JSONObject();
        switch (type) {
            case "1":
            case "2":
                if (custNo != null) {
                    jsonObject.put("custNo", custNo);
                }
                jsonObject.put("mediumNo", bankCard);
                jsonObjects.add(jsonObject);
                JSONObject bankCardInfo = bankCardService.getBankCardInfo(jsonObjects);
                if (ObjectUtils.isEmpty(bankCardInfo)) {
                    return false;
                }
                if ("1".equals(type) && "否".equals(bankCardInfo.getString("sjyh"))) {
                    return false;
                }
                if ("2".equals(type) && "否".equals(bankCardInfo.getString("kjzf"))) {
                    return false;
                }
                break;
            case "3":
                if (custNo != null) {
                    jsonObject.put("custNo", custNo);
                }
                jsonObject.put("mediumNo", bankCard);
                jsonObjects.add(jsonObject);
                JSONObject bankCardOpenDt = bankCardService.getBankCardOpenDt(jsonObjects);
                if (ObjectUtils.isEmpty(bankCardOpenDt) || ObjectUtils.isEmpty(bankCardOpenDt.getString("openDt"))) {
                    return false;
                }
                if (!date.equals(bankCardOpenDt.getString("openDt"))) {
                    return false;
                }
                break;
            case "4":
                jsonObject.put("mediumNo", bankCard);
                jsonObject.put("txDate", date.replace("-", ""));
                jsonObject.put("txBal", deposit);
                jsonObjects.add(jsonObject);
                JSONObject bankCardDeposit = bankCardService.getBankCardDeposit(jsonObjects);
                if (ObjectUtils.isEmpty(bankCardDeposit) || "N".equals(bankCardDeposit.getString("iscondition"))) {
                    return false;
                }
                break;
        }
        return true;
    }

}
